package com.yanqu.road.server.gameplayer.module.activity.shuihu;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.shuihu.ShuiHuUserData;
import com.yanqu.road.entity.activity.shuihu.config.ShuiHuCardConfig;
import com.yanqu.road.entity.activity.shuihu.config.ShuiHuCombConfig;
import com.yanqu.road.entity.activity.shuihu.config.ShuiHuConfig;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogShuiHuComb;
import com.yanqu.road.entity.log.LogShuiHuCompose;
import com.yanqu.road.entity.log.LogShuiHuDraw;
import com.yanqu.road.logic.bussiness.activity.ShuiHuActivityBussiness;
import com.yanqu.road.pb.activity.ShuiHuActivityProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.shuihu.ShuiHuMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.pb.ShuiHuPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Map;

public class ShuiHuModule extends GeneralModule {

    private ShuiHuUserData userData;

    public ShuiHuModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        ActivityInfo activityInfo = ShuiHuMgr.getActivityInfo();
        if (ActivityMgr.activityInShowTime(activityInfo)) {
            userData = ShuiHuActivityBussiness.getShuiHuUserData(activityInfo.getActivityId(), player.getUserId());
            if (userData == null) {
                initUserData();
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        if (userData != null) {
            if (userData.isInsertOption()) {
                ShuiHuActivityBussiness.addShuiHuUserData(userData);
            } else if (userData.isUpdateOption()) {
                ShuiHuActivityBussiness.updateShuiHuUserData(userData);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        syncShuiHuConfig();
        syncShuiHuUserData();
    }

    public void syncShuiHuConfig() {
        ShuiHuConfig shuiHuConfig = ShuiHuMgr.getShuiHuConfig();
        if (shuiHuConfig != null && ActivityMgr.activityInShowTime(shuiHuConfig.getActivityInfo())) {
            ShuiHuActivityProto.SyncShuiHuConfigRespMsg.Builder configRespMsg = ShuiHuPb.parseShuiHuConfigRespMsg(shuiHuConfig, player.getLanguage());
            player.sendPacket(ClientProtocol.U_SHUIHU_ACTIVITY_SYNC_CONFIG, configRespMsg);
        }

    }

    public void syncShuiHuUserData() {
        ShuiHuConfig shuiHuConfig = ShuiHuMgr.getShuiHuConfig();
        if (shuiHuConfig != null && ActivityMgr.activityInShowTime(shuiHuConfig.getActivityInfo())) {
            if (userData != null) {
                ShuiHuActivityProto.ShuiHuUserDataMsg.Builder builder = ShuiHuPb.parseShuiHuUserDataMsg(userData);
                player.sendPacket(ClientProtocol.U_SHUIHU_ACTIVITY_SYNC_USER_DATA, builder);
            }
        }
    }

    public synchronized void initUserData() {
        // 系统未解锁
        if (!SystemOpenMgr.systemOpen(player, eSystemId.ShuiHuActivity.getValue())) {
            return;
        }
        // 没有活动
        ActivityInfo activityInfo = ShuiHuMgr.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }
        // 已经有数据了
        if (userData != null && userData.getActivityId() == activityInfo.getActivityId()) {
            return;
        }

        // 初始化数据
        userData = new ShuiHuUserData();
        userData.setActivityId(activityInfo.getActivityId());
        userData.setUserId(player.getUserId());
        userData.setScore(0);
        userData.setPoint(0);
        userData.setCardProp(new Property());
        userData.setCombProp(new Property());
        userData.setGotCardIdList(new ArrayList<>());
        userData.setAutoReward(false);
        userData.setInsertOption();
    }

    public ShuiHuUserData getUserData() {
        return userData;
    }

    /**
     * 抽卡
     */
    public int drawCard(int itemNo, int roundNo) {
        ShuiHuConfig shuiHuConfig = ShuiHuMgr.getShuiHuConfig();
        if (shuiHuConfig == null || !ActivityMgr.activityInTime(shuiHuConfig.getActivityInfo())) {
            return GameErrorCode.E_SHUIHU_ACTIVITY_NO_OPEN;
        }
        if (userData == null) {
            return GameErrorCode.E_SHUIHU_ACTIVITY_NO_UNLOCK;
        }

        String drawCost = shuiHuConfig.getDrawCost();
        Property property = PropertyHelper.parseStringToProperty(drawCost);

        CurrencyModule module = player.getModule(CurrencyModule.class);
        if (!module.currencyIsEnough(property)) {
            return GameErrorCode.E_SHUIHU_ACTIVITY_DRAW_COST_NO_ENOUGH;
        }

        // 预扣除
        player.getModule(PreReduceModule.class).preReduce(drawCost);

        // 发送到跨服抽卡
        ShuiHuActivityProto.CrossDrawCardReqMsg.Builder builder = ShuiHuActivityProto.CrossDrawCardReqMsg.newBuilder();
        builder.setActivityId(shuiHuConfig.getActivityId());
        builder.setUserId(player.getUserId());
        builder.setServerId(player.getUserInfo().getOriginalServerId());
        builder.setItemNo(itemNo);
        builder.setRoundNo(roundNo);
        builder.setPlayer(PlayerPb.parsePlayerBaseTempMsg(player.getUserInfo()));
        player.sendPacket(CrossProtocol.C2_SHUIHU_ACTIVITY_DRAW_CARD, builder);
        return 0;
    }

    /**
     * 跨服抽卡返回
     */
    public void drawCardFromCross(int ret, int cardId) {
        ShuiHuConfig shuiHuConfig = ShuiHuMgr.getShuiHuConfig();
        if (shuiHuConfig == null || !ActivityMgr.activityInShowTime(shuiHuConfig.getActivityInfo())) {
            return;
        }
        if (userData == null) {
            return;
        }

        // 返还预扣除
        String drawCost = shuiHuConfig.getDrawCost();
        player.getModule(PreReduceModule.class).restorePreReduce(drawCost);

        // 抽卡成功
        if (ret == 0) {
            // 扣消耗
            Property consume = PropertyHelper.parseStringToProperty(drawCost);
            player.getModule(CurrencyModule.class).removeCurrency(consume, eLogMoneyType.ShuiHuActivity, eLogMoneyType.ShuiHuActivityDrawConsume);

            // 加卡片
            userData.getCardProp().addProperty(cardId, BigInteger.ONE);
            if (!userData.getGotCardIdList().contains(cardId)) {
                userData.getGotCardIdList().add(cardId);
            }
            userData.setUpdateOption();

            // 加积分
            ShuiHuCardConfig cardConfig = shuiHuConfig.getCardConfigMap().get(cardId);
            int count = cardConfig.getScore();
            Property reward = new Property();
            reward.addProperty(eItemId.SHUIHU_SCORE_ITEM.getValue(), BigInteger.valueOf(count));
            player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.ShuiHuActivity, eLogMoneyType.ShuiHuActivityDrawReward);

            userData.setScore(userData.getScore() + count);
            // 榜单积分变化
            player.notifyListener(eGamePlayerEventType.ShuiHuScoreRank.getValue(), userData.getScore());

            // 日志
            AutoLogMgr.add(new LogShuiHuDraw(userData.getUserId(), userData.getActivityId(), cardId));
        }
    }

    /**
     * 合成卡片
     */
    public int composeCard(int cardId, int count) {
        ShuiHuConfig shuiHuConfig = ShuiHuMgr.getShuiHuConfig();
        ShuiHuCardConfig cardConfig = shuiHuConfig.getCardConfigMap().get(cardId);

        int point = cardConfig.getComposePoint();
        int needPoint = point * count;

        if (userData.getPoint() < needPoint) {
            return GameErrorCode.E_SHUIHU_ACTIVITY_POINT_NO_ENOUGH;
        }

        // 扣英雄点
        userData.setPoint(userData.getPoint() - needPoint);

        // 加卡片
        userData.getCardProp().addProperty(cardId, BigInteger.valueOf(count));
        if (!userData.getGotCardIdList().contains(cardId)) {
            userData.getGotCardIdList().add(cardId);
        }
        userData.setUpdateOption();

        // 加日志
        AutoLogMgr.add(new LogShuiHuCompose(player.getUserId(), shuiHuConfig.getActivityId(), 1, cardId, count, needPoint));

        return 0;
    }

    /**
     * 分解卡片
     */
    public int decomposeCard(int cardId, int count) {
        ShuiHuConfig shuiHuConfig = ShuiHuMgr.getShuiHuConfig();
        ShuiHuCardConfig cardConfig = shuiHuConfig.getCardConfigMap().get(cardId);

        BigInteger cardCount = userData.getCardProp().getCountByGoodsId(cardId);
        int point = cardConfig.getDecomposePoint();
        int getPoint = point * count;

        if (cardCount.compareTo(BigInteger.valueOf(count)) < 0) {
            return GameErrorCode.E_SHUIHU_ACTIVITY_CARD_NO_ENOUGH;
        }

        // 消耗卡片
        userData.getCardProp().removeProperty(cardId, BigInteger.valueOf(count));

        // 技能生效（没测试过）
//        int patronsTalentAddi = player.getModule(PatronsModule.class).getTalentSkillAddition(eSkillType.ShuiHuRecycleCardAddition.getValue(), 0);
//        int realGetPoint = BigDecimal.valueOf(getPoint)
//                .multiply(BigDecimal.valueOf(patronsTalentAddi + 1000))
//                .divide(BigDecimal.valueOf(1000), 0, BigDecimal.ROUND_UP).intValue();

        // 获得英雄点
        userData.setPoint(userData.getPoint() + getPoint);

        // 加日志
        AutoLogMgr.add(new LogShuiHuCompose(player.getUserId(), shuiHuConfig.getActivityId(), 2, cardId, count, getPoint));

        return 0;
    }

    /**
     * 领取组合奖励
     */
    public int getCombReward(int combId, int times) {
        ShuiHuConfig shuiHuConfig = ShuiHuMgr.getShuiHuConfig();
        ShuiHuCombConfig combConfig = shuiHuConfig.getCombConfigMap().get(combId);

        Property consume = PropertyHelper.parseStringToProperty(combConfig.getCondition());
        consume.rideProperty(times);
        Property cardProp = userData.getCardProp();

        // 是否达到上限次数
        BigInteger nextCombTimes = userData.getCombProp().getCountByGoodsId(combId).add(BigInteger.valueOf(times));
        int maxTimes = combConfig.getMaxTimes();
        if (nextCombTimes.compareTo(BigInteger.valueOf(maxTimes)) > 0) {
            return GameErrorCode.E_SHUIHU_ACTIVITY_COMB_REWARD_LIMIT;
        }

        // 卡片是否足够
        for (Map.Entry<Integer, BigInteger> entry : consume.getGoods().entrySet()) {
            BigInteger cardCount = cardProp.getCountByGoodsId(entry.getKey());
            if (cardCount.compareTo(entry.getValue()) < 0) {
                return GameErrorCode.E_SHUIHU_ACTIVITY_CARD_NO_ENOUGH;
            }
        }

        // 扣卡片
        for (Map.Entry<Integer, BigInteger> entry : consume.getGoods().entrySet()) {
            cardProp.removeProperty(entry.getKey(), entry.getValue());
        }

        // 加组合次数
        userData.getCombProp().addProperty(combId, BigInteger.valueOf(times));
        userData.setUpdateOption();

        // 加奖励
        Property reward = PropertyHelper.parseStringToProperty(combConfig.getReward());
        reward.rideProperty(times);
        player.getModule(CurrencyModule.class).addCurrency(
                reward,
                eLogMoneyType.ShuiHuActivity, eLogMoneyType.ShuiHuActivityCombReward);

        // 检查组合
        int combTimes = ShuiHuMgr.calAllCombTimes(shuiHuConfig, userData);
        player.notifyListener(eGamePlayerEventType.ShuiHuAllCombTimes.getValue(), combTimes);

        // 返回
        ShuiHuActivityProto.GetShuiHuCombRewardRespMsg.Builder builder = ShuiHuActivityProto.GetShuiHuCombRewardRespMsg.newBuilder();
        builder.setRet(0);
        builder.setReward(PropertyHelper.parsePropertyToString(reward));
        player.sendPacket(ClientProtocol.U_SHUIHU_ACTIVITY_GET_COMB_REWARD, builder);


        // 加日志
        AutoLogMgr.add(new LogShuiHuComb(player.getUserId(), shuiHuConfig.getActivityId(), combId, times));

        return 0;
    }


}
